import datetime
from .conn_mysql import ConnectMysql


class MysqlApi(ConnectMysql):

    def login_notify(self, phone, pass_word):

        sql = "SELECT * FROM account WHERE phone=%s and pass_word=%s"

        result = self.select_one(sql, (phone, pass_word))

        if not result:

            return {
                "status": -1,
                "errorCode": 3,
                "errorMsg": '账号或者密码输入有误',
                "resultBody": None,
            }

        return {
                "status": 1,
                "errorCode": None,
                "errorMsg": None,
                "resultBody": '验证通过',
            }


    def insert_user(self, phone, pass_word):

        sql_del = "DELETE FROM account WHERE phone=%s"

        sql = "INSERT INTO account(phone, pass_word) VALUES (%s, %s);"

        self.delete_info(sql_del, (phone,))

        self.insert_info(sql, (phone, pass_word))

    def verify_phone(self, phone, verify_code):
        '''验证码是否合法'''

        sql = 'SELECT * FROM phone_verify WHERE verify_code=%s and phone=%s'

        result = self.select_one(sql, (verify_code, phone))

        if not result:

            return {
                "status": -1,
                "errorCode": 1,
                "errorMsg": '验证码输入有误，请重新确认',
                "resultBody": None,
            }

        time_delta = datetime.timedelta(minutes=5)#有效时间量
        regedate = result['regedate']#datetime类型

        # print('32行的时间：',regedate)

        if (regedate + time_delta) < datetime.datetime.now():#时间失效

            return {
                "status": -1,
                "errorCode": 2,
                "errorMsg": '验证码超时，请重新申请新验证码',
                "resultBody": None,
            }

        else:

            return {
                "status": 1,
                "errorCode": None,
                "errorMsg": None,
                "resultBody": '验证通过',
            }
    def can_i_send_sms(self, phone):
        '''phone是否可以发短信'''

        sql = 'SELECT * FROM phone_verify WHERE phone=%s ORDER BY regedate DESC LIMIT 0,1'

        result = self.select_one(sql, (phone,))

        if result:

            regedate = result['regedate']

            time_delta = datetime.timedelta(minutes=5)

            if (regedate + time_delta) > datetime.datetime.now():

                return False

        return True

    def insert_verify_code(self, phone, verify_code):
        '''将验证码插入到数据库存中'''

        sql = 'INSERT INTO phone_verify(phone, verify_code) VALUES (%s, %s)'

        self.insert_info(sql, (phone, verify_code))












        

